<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form v-loading="saveLoading" size="small" ref="form" :model="form" :rules="rules" label-width="120px" @submit.native.prevent>
        <el-form-item label="关联房屋：" prop="houseType">
          <el-input v-model="form.leaseCertificateNumber" placeholder="所属房屋" style="width: 50%" :disabled="isDisabled">
          </el-input>
        </el-form-item>
        <el-form-item label="关联承租人：" prop="tenantName">
          <template slot-scope="scope">
            <el-input v-model="form.tenantName" placeholder="关联承租人" style="width: 50%" :disabled="isDisabled">
            </el-input>
            <el-button type="primary" size="mini" style="margin-left: 10px" @click="openLesseeDialog(scope.row)" :disabled="isDisabled">选择承租人
            </el-button>
          </template>
        </el-form-item>
        <el-form-item label="收费标准：" prop="unitPricePerSquare">
          <el-input v-model="form.unitPricePerSquare" placeholder="收费标准" :disabled="true" style="width: 50%">
          </el-input>
        </el-form-item>
        <el-form-item label="面积：" prop="usableArea">
          <el-input v-model="form.usableArea" placeholder="面积" :disabled="true" style="width: 50%">
          </el-input>
        </el-form-item>

        <el-form-item label="月租金：" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="月租金" :disabled="true" style="width: 50%">
          </el-input>
        </el-form-item>
        <el-form-item label="租赁合同编号：" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="租赁合同编号" style="width: 50%" :disabled="isDisabled">
          </el-input>
        </el-form-item>
        <el-form-item label="合同周期：" prop="leaseCertificateNumber">
          <el-date-picker style="width: 50%" :disabled="isDisabled"
              v-model="form.leaseCertificateNumber"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="状态：" prop="status">
          <el-select v-model="form.status" placeholder="状态" style="width: 450px">
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                     @click="handlerSubmit" v-has-permi="['admin:house:information:save']">保存
          </el-button>
          <el-button @click="close">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 承租人选择弹窗 -->
    <el-dialog title="选择承租人" :visible.sync="dialogVisible" width="50%">
      <el-input
          v-model="listPram.yhkeyword"
          placeholder="输入姓名或身份证号搜索"
          @keyup.enter="handleSearch"
          clearable>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>

      <el-table
          :data="filteredTableData"
          border
          style="width: 100%; margin-top: 20px">
        <el-table-column prop="tenantName" label="姓名"></el-table-column>
        <el-table-column prop="tenantIdCard" label="身份证号"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button
                type="text"
                @click="selectLessee(scope.row)">选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


  </div>
</template>
<script>
import {amountSave} from "@/api/payment";
import { listNew} from "@/api/lessee";
import {detail} from "@/api/leaseInformation";

export default {
  data() {
    return {
      isDisabled: this.$route.params.isDisabled==='1'?true:false,
      form: {
        id: null,
        leaseCertificateNumber:'',
        areaName:'',
        streetName:'',
        usableArea:'',
        totalPrice:'',
        contractNumber:'',
        status:'',
        unitPricePerSquare:'',
        paymentStart:'',
        paymentEnd:'',
      },
      // 承租人选择相关
      dialogVisible: false,
      currentRow: null,
      filteredTableData: [],
      tableLoading: false,
      listPram: {
        page: 1,
        limit: 10,
        yhkeyword: '',
      },
      rules: {
        houseType: [{required: true, message: '请选择房屋类型', trigger: ['blur']}],
        leaseCertificateNumber: [{required: true, message: '请填写租赁证编号', trigger: ['blur']}],
        areaName: [{required: true, message: '请选择片区', trigger: ['blur']}],
        streetName: [{required: true, message: '请选择街（巷、路）', trigger: ['blur']}],
        courtyardNumber: [{required: true, message: '请选择号（楼、院）', trigger: ['blur']}],
        unitNumber: [{required: true, message: '请选择unitNumber', trigger: ['blur']}],
        buildingNumber: [{required: true, message: '请选择楼号', trigger: ['blur']}],
        roomNumber: [{required: true, message: '请选择房号', trigger: ['blur']}],
      },
      saveLoading: false,
      formLoading: false,
      statusOptions: [{
        value: '1',
        label: '待审核'
      }, {
        value: '2',
        label: '生效中'
      }, {
        value: '3',
        label: '已终止'
      }, {
        value: '4',
        label: '争议处理中'
      }],
    }
  },
  mounted() {
    if (this.$route.params.id) {
      this.getDetail();
    }
  },
  methods: {
    getDetail() {

      this.saveLoading = true;
      detail({id:this.$route.params.id}).then((res) => {
        this.form = res
        this.close();
      }).finally(() => {
        this.saveLoading = false
      })
    },
    handlerSubmit() {
      if (this.saveLoading) {
        return
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        amountSave(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    onSubmit() {
      this.dialogVisible = true; // 打开弹窗
    },
    close() {
      this.$emit('hideEditDialog');
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
    },
    // 打开选择承租人弹窗
    openLesseeDialog(row) {
      this.currentRow = row;
      this.dialogVisible = true;
      this.listPram.yhkeyword = '';
      this.filteredTableData = [];
    },
    // 搜索承租人
    handleSearch() {
      if (!this.listPram.yhkeyword.trim()) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      this.tableLoading = true;
      listNew(this.listPram).then(res => {
        this.filteredTableData = res.list;
        if (this.filteredTableData.length === 0) {
          this.$message.info('未找到匹配结果');
        }
      }).finally(() => {
        this.tableLoading = false;
      });
    },
    // 选择承租人
    selectLessee(row) {
      this.$set(this.currentRow, 'tenantName', row.tenantName);
      this.$set(this.currentRow, 'tenantIdCardFour', row.tenantIdCard.slice(-4));
      this.dialogVisible = false;
      this.$message.success('承租人选择成功');
    },



  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


/* 自定义弹窗样式 */
.right-dialog {
  position: fixed;
  top: 0;
  left:60%; /* 定位到页面最右侧 */
  bottom: 0;
  margin: 0 !important; /* 清除默认 margin */
  height: 100vh !important; /* 高度占满整个视口 */
  width: 40% !important; /* 宽度为 30% */
  transform: none !important; /* 清除默认 transform */
  .el-dialog__header {
    text-align: left;
    padding: 20px; /* 根据需要调整 */
  }

  .el-dialog__body {
    height: calc(100% - 130px); /* 假设头部和底部总高度是100px, 可以根据实际情况调整 */
    overflow-y: auto; /* 如果内容超出，启用垂直滚动 */
  }

  .el-dialog__footer {
    padding: 10px; /* 根据需要调整 */
    text-align: right;
  }
}
::v-deep .el-textarea .el-input__count {
  position: absolute;
  right: -50px;
  bottom: 0;
  background: transparent;
}

</style>
